package logic

import (
	"context"
	"fmt"
	"hui-hui/models"
	"hui-hui/pkg"

	"hui-hui/hui_hui_rpc/hui_hui_rpc"
	"hui-hui/hui_hui_rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestLogic {
	return &RestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RestLogic) Rest(in *hui_hui_rpc.RestRequest) (*hui_hui_rpc.RestResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("%s:%s", "rest", in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	var user models.User
	if models.DB.Where("account = ?", in.Phone).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("该账号已存在")
	}
	user.Account = in.Phone
	user.Password = pkg.MD5(in.Password)
	if models.DB.Create(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &hui_hui_rpc.RestResponse{}, nil
}
